package com.simplehire.controller;

import com.simplehire.model.InterviewResult;
import com.simplehire.model.User;
import com.simplehire.service.FileProcessingService;
import com.simplehire.service.InterviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/interview")
public class InterviewController {

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private FileProcessingService fileProcessingService;

    /**
     * 显示面试主页
     */
    @GetMapping
    public String showInterviewPage(Model model, Authentication authentication) {
        User currentUser = (User) authentication.getPrincipal();
        
        // 获取用户统计信息
        InterviewService.UserInterviewStats stats = interviewService.getUserStats(currentUser);
        model.addAttribute("stats", stats);
        
        // 获取最近的面试记录
        List<InterviewResult> recentResults = interviewService.getRecentInterviewResults(currentUser, 5);
        model.addAttribute("recentResults", recentResults);
        
        // 文件上传信息
        model.addAttribute("maxFileSize", fileProcessingService.getMaxFileSizeMB());
        model.addAttribute("supportedTypes", fileProcessingService.getSupportedFileTypes());
        
        return "interview";
    }

    /**
     * 处理简历文件上传
     */
    @PostMapping("/upload")
    public String uploadResume(@RequestParam("resumeFile") MultipartFile file,
                              Authentication authentication,
                              RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证文件
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请选择要上传的简历文件。");
                return "redirect:/interview";
            }
            
            if (!fileProcessingService.isValidFileType(file.getOriginalFilename())) {
                redirectAttributes.addFlashAttribute("error", 
                    "不支持的文件格式。支持的格式：" + fileProcessingService.getSupportedFileTypes());
                return "redirect:/interview";
            }
            
            if (!fileProcessingService.isValidFileSize(file.getSize())) {
                redirectAttributes.addFlashAttribute("error", 
                    "文件大小不能超过" + fileProcessingService.getMaxFileSizeMB() + "MB。");
                return "redirect:/interview";
            }
            
            // 开始面试流程
            InterviewResult result = interviewService.startInterviewWithFile(currentUser, file);
            
            redirectAttributes.addFlashAttribute("message", "简历上传成功，AI已生成面试问题！");
            return "redirect:/interview/questions/" + result.getId();
            
        } catch (IllegalArgumentException e) {
            // 文件处理相关的错误（如文件格式不支持、没有找到文本内容等）
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/interview";
        } catch (UnsupportedOperationException e) {
            // 不支持的操作（如.doc格式）
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/interview";
        } catch (Exception e) {
            // 其他未知错误
            redirectAttributes.addFlashAttribute("error", "处理简历文件时出错：" + e.getMessage());
            return "redirect:/interview";
        }
    }

    /**
     * 处理简历文本输入
     */
    @PostMapping("/text")
    public String submitResumeText(@RequestParam("resumeText") String resumeText,
                                  Authentication authentication,
                                  RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证文本内容
            if (resumeText == null || resumeText.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请输入简历内容。");
                return "redirect:/interview";
            }
            
            if (resumeText.trim().length() < 50) {
                redirectAttributes.addFlashAttribute("error", "简历内容太短，请提供更详细的信息。");
                return "redirect:/interview";
            }
            
            // 开始面试流程
            InterviewResult result = interviewService.startInterviewWithText(currentUser, resumeText.trim());
            
            redirectAttributes.addFlashAttribute("message", "简历提交成功，AI已生成面试问题！");
            return "redirect:/interview/questions/" + result.getId();
            
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "处理简历内容时出错：" + e.getMessage());
            return "redirect:/interview";
        }
    }

    /**
     * 显示面试问题页面
     */
    @GetMapping("/questions/{id}")
    public String showQuestions(@PathVariable Long id, 
                               Model model, 
                               Authentication authentication) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        Optional<InterviewResult> resultOpt = interviewService.getInterviewResult(id);
        if (resultOpt.isEmpty()) {
            model.addAttribute("error", "面试记录不存在。");
            return "redirect:/interview";
        }
        
        InterviewResult result = resultOpt.get();
        
        // 检查权限
        if (!result.getUser().getId().equals(currentUser.getId())) {
            model.addAttribute("error", "无权限访问此面试记录。");
            return "redirect:/interview";
        }
        
        // 如果已经有答案，重定向到结果页面
        if (result.getUserAnswers() != null && !result.getUserAnswers().trim().isEmpty()) {
            return "redirect:/interview/result/" + id;
        }
        
        model.addAttribute("result", result);
        model.addAttribute("questions", parseQuestions(result.getAiQuestions()));
        
        return "questions";
    }

    /**
     * 提交面试答案
     */
    @PostMapping("/submit/{id}")
    public String submitAnswers(@PathVariable Long id,
                               @RequestParam("answers") String answers,
                               Authentication authentication,
                               RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证答案内容
            if (answers == null || answers.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请回答面试问题。");
                return "redirect:/interview/questions/" + id;
            }
            
            // 提交答案并获取评估
            InterviewResult result = interviewService.submitAnswers(id, answers.trim());
            
            // 检查权限
            if (!result.getUser().getId().equals(currentUser.getId())) {
                redirectAttributes.addFlashAttribute("error", "无权限访问此面试记录。");
                return "redirect:/interview";
            }
            
            redirectAttributes.addFlashAttribute("message", "答案提交成功，AI评估已完成！");
            return "redirect:/interview/result/" + id;
            
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "提交答案时出错：" + e.getMessage());
            return "redirect:/interview/questions/" + id;
        }
    }

    /**
     * 显示面试结果页面
     */
    @GetMapping("/result/{id}")
    public String showResult(@PathVariable Long id, 
                            Model model, 
                            Authentication authentication) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        Optional<InterviewResult> resultOpt = interviewService.getInterviewResult(id);
        if (resultOpt.isEmpty()) {
            model.addAttribute("error", "面试记录不存在。");
            return "redirect:/interview";
        }
        
        InterviewResult result = resultOpt.get();
        
        // 检查权限
        if (!result.getUser().getId().equals(currentUser.getId())) {
            model.addAttribute("error", "无权限访问此面试记录。");
            return "redirect:/interview";
        }
        
        // 如果还没有答案，重定向到问题页面
        if (result.getUserAnswers() == null || result.getUserAnswers().trim().isEmpty()) {
            return "redirect:/interview/questions/" + id;
        }
        
        model.addAttribute("result", result);
        model.addAttribute("questions", parseQuestions(result.getAiQuestions()));
        model.addAttribute("answers", parseAnswers(result.getUserAnswers()));
        
        return "result";
    }

    /**
     * 显示面试历史页面
     */
    @GetMapping("/history")
    public String showHistory(@RequestParam(defaultValue = "0") int page,
                             @RequestParam(defaultValue = "10") int size,
                             Model model,
                             Authentication authentication) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        Page<InterviewResult> historyPage = interviewService.getUserInterviewHistory(currentUser, page, size);
        
        model.addAttribute("historyPage", historyPage);
        model.addAttribute("currentPage", page);
        
        return "history";
    }

    /**
     * 删除面试记录
     */
    @PostMapping("/delete/{id}")
    public String deleteResult(@PathVariable Long id,
                              Authentication authentication,
                              RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            interviewService.deleteInterviewResult(id, currentUser);
            redirectAttributes.addFlashAttribute("message", "面试记录已删除。");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除记录时出错：" + e.getMessage());
        }
        
        return "redirect:/interview/history";
    }

    /**
     * 解析AI生成的问题
     */
    private List<String> parseQuestions(String questionsText) {
        if (questionsText == null || questionsText.trim().isEmpty()) {
            return List.of("1. 请介绍一下您的技术背景和工作经验？", 
                          "2. 您在项目中遇到过哪些技术挑战，是如何解决的？", 
                          "3. 您对未来的职业发展有什么规划？");
        }
        
        // 按行分割并提取问题
        return List.of(questionsText.split("\n"))
                .stream()
                .map(String::trim)
                .filter(line -> !line.isEmpty())
                .filter(line -> line.matches(".*问题\\d+.*：.*") || line.matches("\\d+\\..*"))
                .map(line -> {
                    // 如果是"问题X："格式，提取冒号后的内容
                    if (line.contains("：")) {
                        String[] parts = line.split("：", 2);
                        return parts.length > 1 ? parts[1].trim() : line;
                    }
                    return line;
                })
                .toList();
    }

    /**
     * 解析用户答案
     */
    private List<String> parseAnswers(String answersText) {
        if (answersText == null) {
            return List.of();
        }
        
        return List.of(answersText.split("\n\n"))
                .stream()
                .map(String::trim)
                .filter(line -> !line.isEmpty())
                .toList();
    }

    /**
     * API接口 - 测试AI连接
     */
    @GetMapping("/api/test-ai")
    @ResponseBody
    public boolean testAIConnection() {
        return interviewService.testAIConnection();
    }
}